package com.jml.task.service;

import com.jml.task.entity.LockInfo;
import com.jml.task.lock.impl.ZkTemporaryOrderNodeLock;
import com.jml.task.mapper.UserMapper;
import com.jml.task.utils.TranslationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@Slf4j
public class MyService {
    @Autowired
    private ZkTemporaryOrderNodeLock zkTemporaryOrderNodeLock;

    @Autowired
    private TranslationUtils translationUtils;

    @RequestMapping("/testLock")
    public String testLock() {
        try {
            zkTemporaryOrderNodeLock.getLock();
            log.info("获取锁成功 执行业务逻辑");
            zkTemporaryOrderNodeLock.unLock();
        } catch (Exception e) {
            zkTemporaryOrderNodeLock.unLock();
        }
        return "ok";
    }

    @Autowired
    private UserMapper userMapper;

    private  Map<String, TransactionStatus> map = new ConcurrentHashMap<>();
    private  Map<String, TranslationUtils> map001 = new ConcurrentHashMap<>();


    @RequestMapping("/dbLock")
    public String dbLock() {
        System.out.println("dbLock-translationUtils:"+translationUtils);
        TransactionStatus begin = translationUtils.begin();
        try {
            userMapper.insert("jml" + System.currentTimeMillis(), 20);
            map.put("begin",begin);
            map001.put("translationUtils",translationUtils);
            System.out.println("dbLock-begin:"+begin);
            System.out.println("dbLock-translationUtils:"+translationUtils);
//            translationUtils.commit(begin);
        } catch (Exception e) {
            translationUtils.rollback(begin);
        }
        return "ok";
    }

    @RequestMapping("/dbUnLock")
    public String dbUnLock() {
        TransactionStatus transactionStatus = map.get("begin");
        TranslationUtils translationUtils001 = map001.get("translationUtils");
        System.out.println("dbUnLock-transactionStatus:"+transactionStatus);
        System.out.println("dbUnLock-translationUtils001:"+translationUtils001);
        System.out.println("dbUnLock-translationUtils:"+translationUtils);
        translationUtils.rollback(transactionStatus);
        return "ok";
    }
}
